package com.greenline.search.report.util;

import com.greenline.search.report.entity.SearchWord;
import com.greenline.search.report.model.Configuration;
import com.greenline.search.test.utils.JSONStreamParserForAnalyze;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by liulei on 5/22/14.
 */
public class SearchWordListUtil {
    public static final Logger logger = LoggerFactory.getLogger(SearchWordListUtil.class);
    //把每个文件里的词都聚合到searchWordList
    public static void initSearchWordList(List<String> logNameList, List<SearchWord> searchWordList){
        for(String fileName : logNameList){
            logger.info("Read file " + fileName + ".txt in process...");
            String filePath = Configuration.ROOT_PATH+fileName.substring(0,6)+
                    Configuration.FOLDER_BACKSLASH+fileName+".txt";
            List<String> fileContents = FileUtils.readFileAsString(filePath,"UTF-8");
            for(String content : fileContents){
                SearchWord searchWord;
                String[] contentSplit = content.split("\"\t\"");
                try {
                    if(contentSplit[0].length() > 1){
                        String word = contentSplit[0].substring(1,contentSplit[0].length()).trim();
                        if(word.contains("xE") || word.trim().length() <= 0){
                            continue;
                        }
                        searchWord = JSONStreamParserForAnalyze.getWordType(word);
                        searchWord.setText(word);
                        try {
                            searchWord.setFrequency(Integer.parseInt(contentSplit[1]));
                        }catch(ArrayIndexOutOfBoundsException ex){
                            continue;
                        }
                        if(searchWordList.contains(searchWord)){
                            int wordIndex = searchWordList.indexOf(searchWord);
                            SearchWord originalSearchWord = searchWordList.get(wordIndex);
                            searchWord.setFrequency(searchWord.getFrequency()+originalSearchWord.getFrequency());
                            searchWordList.set(wordIndex,searchWord);
                        } else {
                            searchWordList.add(searchWord);
                        }
                    }else {
                        continue;
                    }
                }catch (StringIndexOutOfBoundsException e){
                    e.printStackTrace();
                }
            }
        }
        logger.info("The search word size is {}", searchWordList.size());
    }
}
